package com.slofzx.nuoda.evaluation.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.slofzx.nuoda.common.config.Type;
import com.slofzx.nuoda.common.exception.ServiceException;
import com.slofzx.nuoda.common.util.IdGen;
import com.slofzx.nuoda.custom.template.dao.TemplateDAO;
import com.slofzx.nuoda.custom.template.entity.TemplateInfo;
import com.slofzx.nuoda.evaluation.project.entity.BatchInfo;
import com.slofzx.nuoda.evaluation.project.entity.ExportTemplateDetail;
import com.slofzx.nuoda.evaluation.project.dto.ExportTemplateDetailDTO;
import com.slofzx.nuoda.evaluation.project.enums.*;
import com.slofzx.nuoda.evaluation.project.util.BusiUtil;
import com.slofzx.nuoda.evaluation.project.vo.ExportTemplateDetailVO;
import com.slofzx.nuoda.evaluation.project.dao.ExportTemplateDetailDAO;
import com.slofzx.nuoda.evaluation.project.service.ExportTemplateDetailService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.slofzx.nuoda.common.enums.CommonResultEnum;
import com.slofzx.nuoda.common.enums.ServiceResult;
import com.slofzx.nuoda.common.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * 模版详情表服务实现类
 *
 * @author nuoda
 * @since 2024-02-29 08:36:54
 */
@Service("exportTemplateDetailService")
public class ExportTemplateDetailServiceImpl extends BaseServiceImpl implements ExportTemplateDetailService {
    @Autowired
    private ExportTemplateDetailDAO exportTemplateDetailDAO;
    @Autowired
    private TemplateDAO templateDAO;

    private static final String MOVE_UP = "up";
    private static final String MOVE_DOWN = "down";

    /**
     * 将数据表数据转换为返回数据类型
     *
     * @param entity 数据表对应类
     * @return 实例对象
     */
    protected ExportTemplateDetailVO parseEntity2VO(ExportTemplateDetail entity) {
        ExportTemplateDetailVO vo = new ExportTemplateDetailVO();
        vo.setId(entity.getId());
        vo.setName(entity.getName());
        vo.setAreaMark(entity.getAreaMark());
        vo.setProductProperty(entity.getProductProperty());
        vo.setCapacityType(entity.getCapacityType());
        vo.setDisplacementMethod(entity.getDisplacementMethod());
        vo.setRegion(entity.getRegion());
        vo.setPoolType(entity.getPoolType());
        vo.setPassed(entity.getPassed());
        vo.setTemplateId(entity.getTemplateId());
        vo.setSort(entity.getSort());
        vo.setCreateUser(entity.getCreateUser());
        vo.setCreateTime(entity.getCreateTime());
        return vo;
    }

    /**
     * 将数据传递类转换为数据表数据类
     *
     * @param dto 数据传递类实例
     * @return 实例对象
     */
    protected ExportTemplateDetail parseDTO2Entity(ExportTemplateDetailDTO dto) {
        ExportTemplateDetail entity = new ExportTemplateDetail();
        entity.setId(dto.getId());
        entity.setName(dto.getName());
        entity.setAreaMark(dto.getAreaMark());
        entity.setProductProperty(dto.getProductProperty());
        entity.setCapacityType(dto.getCapacityType());
        entity.setDisplacementMethod(dto.getDisplacementMethod());
        entity.setRegion(dto.getRegion());
        entity.setPoolType(dto.getPoolType());
        entity.setPassed(dto.getPassed());
        entity.setTemplateId(dto.getTemplateId());
        return entity;
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ExportTemplateDetailVO queryById(String id) {
        ExportTemplateDetail entity = this.exportTemplateDetailDAO.selectById(id);
        if (entity == null) {
            return null;
        }
        return parseEntity2VO(entity);
    }

    /**
     * 查询多条数据
     *
     * @param dto 数据传递类实例对象
     * @return 对象列表
     */
    @Override
    public List<ExportTemplateDetailVO> queryList(ExportTemplateDetailDTO dto) {
        //mybatis-plus 写法示例
        //IPage<ExportTemplateDetail> pageResult = this.evaModelDAO.selectPage(new Page<>(dto.getPageNo(),dto.getPageSize()),null);
        //List<ExportTemplateDetail> dataList = pageResult.getRecords();
        //dto.setCount((int) pageResult.getTotal());
        final String templateId = dto.getTemplateId();
        final TemplateInfo templateInfo = templateDAO.selectById(templateId);
        if (Objects.isNull(templateInfo)) {
            return Collections.emptyList();
        }
        List<ExportTemplateDetail> dataList = this.exportTemplateDetailDAO.queryList(dto);
        if (null == dataList || dataList.isEmpty()) {
            return Collections.emptyList();
        }
        final boolean isOil = ProductTypeEnum.OIL.getId().equals(templateInfo.getTag());
        List<ExportTemplateDetailVO> resultList = new ArrayList(dataList.size());
        for (ExportTemplateDetail item : dataList) {
            ExportTemplateDetailVO vo = parseEntity2VO(item);
            List<String> nameList = Arrays.asList(
                    convertDataName(item.getAreaMark(), AreaMarkEnum.class),
                    convertDataName(item.getRegion(), isOil ? OilRegionEnum.class : GasRegionEnum.class),
                    convertDataName(item.getCapacityType(), isOil ? OilCapacityTypeEnum.class : GasCapacityTypeEnum.class),
                    convertDataName(item.getDisplacementMethod(), isOil ? OilDisplacementMethodEnum.class : GasDisplacementMethodEnum.class),
                    convertDataName(item.getPoolType(), isOil ? OilPoolTypeEnum.class : GasPoolTypeEnum.class),
                    convertDataName(item.getPassed(), PassTypeEnum.class)
            );
            vo.setCustomType(BusiUtil.generateBusiKey(nameList.toArray(new String[0]), ","));
            resultList.add(vo);
        }
        resultList.sort(Comparator.comparing(ExportTemplateDetailVO::getSort));
        // TODO 添加其他关联查询数据
        return resultList;
    }

    private String convertDataName(String type, Class<? extends Type> clazz) {
        final Type enumById = BusiUtil.getEnumById(type, clazz);
        if (Objects.isNull(enumById)) {
            return null;
        }
        return enumById.getName();
    }

    /**
     * 新增数据
     *
     * @param dto 实例对象
     * @return 操作结果
     */
    @Override
    @Transactional
    public ServiceResult create(ExportTemplateDetailDTO dto) {
        // TODO 添加校验逻辑
        ExportTemplateDetail entity = parseDTO2Entity(dto);
        final Integer count = exportTemplateDetailDAO.countByTemplateId(dto.getTemplateId());
        preInsert(entity);
        entity.setSort(count);
        this.exportTemplateDetailDAO.insert(entity);
        return CommonResultEnum.SUCCESS;
    }

    /**
     * 检查任务名称是否重复
     *
     * @param name
     */
    private void checkDuplicateName(String name, String id) {
        LambdaQueryWrapper<ExportTemplateDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ExportTemplateDetail::getName, name);
        if (StringUtils.isNotEmpty(id)) {
            queryWrapper.ne(ExportTemplateDetail::getId, id);
        }
        final Long count = exportTemplateDetailDAO.selectCount(queryWrapper);
        if (count > 0) {
            throw new ServiceException("任务名称重复，请修改后提交", null, null);
        }
    }

    /**
     * 操作数据上移下移
     *
     * @param type
     * @param id
     */
    private void move(String type, String id) {
        final ExportTemplateDetail exportTemplateDetail = exportTemplateDetailDAO.selectById(id);
        final Integer sort = exportTemplateDetail.getSort();
        Integer newSort = Integer.valueOf(sort);
        if (MOVE_UP.equals(type)) {
            exportTemplateDetail.setSort(sort - 1);
            newSort--;
        } else {
            exportTemplateDetail.setSort(sort + 1);
            newSort++;
        }
        final ExportTemplateDetailDTO dto = new ExportTemplateDetailDTO();
        dto.setTemplateId(exportTemplateDetail.getTemplateId());
        dto.setSort(newSort);
        final List<ExportTemplateDetail> dataList = exportTemplateDetailDAO.queryList(dto);
        if (dataList.size() == 1) {
            dataList.get(0).setSort(sort);
            dataList.add(exportTemplateDetail);
            updateBatchById(dataList, exportTemplateDetailDAO, ExportTemplateDetail.class);
        }

    }

    /**
     * 修改数据
     *
     * @param dto 实例对象
     * @return 操作结果
     */
    @Override
    @Transactional
    public ServiceResult update(ExportTemplateDetailDTO dto) {
        String id = dto.getId();
        if (StringUtils.isEmpty(id)) {
            return CommonResultEnum.NOT_EXIST;
        }
        ExportTemplateDetail entity = this.exportTemplateDetailDAO.selectById(id);
        if (entity == null) {
            return CommonResultEnum.NOT_EXIST;
        }
        // TODO 添加其他校验逻辑，如数据权限
       // checkDuplicateName(dto.getName(),dto.getId());
        entity.setName(dto.getName());
        entity.setAreaMark(dto.getAreaMark());
        entity.setProductProperty(dto.getProductProperty());
        entity.setCapacityType(dto.getCapacityType());
        entity.setDisplacementMethod(dto.getDisplacementMethod());
        entity.setRegion(dto.getRegion());
        entity.setPoolType(dto.getPoolType());
        entity.setPassed(dto.getPassed());
        entity.setTemplateId(dto.getTemplateId());
        this.exportTemplateDetailDAO.updateById(entity);
        return CommonResultEnum.SUCCESS;
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 操作结果
     */
    @Override
    @Transactional
    public ServiceResult deleteById(String id) {
        final ExportTemplateDetail exportTemplateDetail = exportTemplateDetailDAO.selectById(id);

        // TODO 添加校验逻辑，如数据权限
        this.exportTemplateDetailDAO.deleteById(id);
        // 删除数据时重置排序字段的排序数
        final ExportTemplateDetailDTO dto = new ExportTemplateDetailDTO();
        dto.setTemplateId(exportTemplateDetail.getTemplateId());
        final List<ExportTemplateDetail> exportTemplateDetails = exportTemplateDetailDAO.queryList(dto);
        if (CollectionUtils.isEmpty(exportTemplateDetails)) {
            return CommonResultEnum.SUCCESS;
        }
        exportTemplateDetails.sort(Comparator.comparing(ExportTemplateDetail::getSort));
        for (int i = 0; i < exportTemplateDetails.size(); i++) {
            exportTemplateDetails.get(i).setSort(i);
        }
        updateBatchById(exportTemplateDetails, exportTemplateDetailDAO, ExportTemplateDetail.class);

        return CommonResultEnum.SUCCESS;
    }

    @Override
    @Transactional
    public ServiceResult moveUp(String id) {
        move(MOVE_UP, id);
        return CommonResultEnum.SUCCESS;
    }

    @Override
    @Transactional
    public ServiceResult moveDown(String id) {
        move(MOVE_DOWN, id);
        return CommonResultEnum.SUCCESS;
    }

    /**
     * 复制
     * @param formId
     * @param toId
     */
    @Override
    public void copy(String formId, String toId) {
        final ExportTemplateDetailDTO dto = new ExportTemplateDetailDTO();
        dto.setTemplateId(formId);
        final List<ExportTemplateDetail> exportTemplateDetails = exportTemplateDetailDAO.queryList(dto);
        if (CollectionUtils.isEmpty(exportTemplateDetails)) {
            return;
        }
        final String userId = getUserId();
        for (ExportTemplateDetail detail : exportTemplateDetails) {
            detail.setTemplateId(toId);
            detail.setId(IdGen.uuid());
            detail.setCreateTime(new Date());
            detail.setCreateUser(userId);
        }
        saveBatch(exportTemplateDetails, exportTemplateDetailDAO, ExportTemplateDetail.class);
    }
}
